How to create an object in JavaScript?
How to create an object in JavaScript? so that no anyone can change it.
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
Khushi Singh
25-Dec-2024You can create an object in JavaScript that cannot be modified using the Object.freeze() method. The Object.freeze() method "freezes" an object, which means its properties cannot be changed, nor can you add new properties. Let's break it down:
Example:
In this example, by calling Object.freeze(person), then any attempts to change a name or add a new city will do nothing. The object remains exactly as it is when frozen – no more changes allowed!
But Wait—What if My Object Has Other Objects Inside It?
By default, Object.freeze() only prevents modification of the outer properties of the object. Therefore, if it contains other objects inside, they can still be changed unless you freeze those too.
Example:
How to Make the Object Fully Immutable (Deep Freeze):
If you want to ensure that every property of the object, including those that might be nested inside other objects, are immutable, then you have to perform a "deep freeze." Here's how
Now, deepUser is an object that is and everything inside it immutable, i.e., at any point no changes are allowed inside.
If you’re interested in learning more about JavaScript objects, check out this detailed article on JavaScript Objects.
Anubhav Kumar
18-Dec-2024In JavaScript, there are multiple ways to create an object. Here are the most common methods:
1. Using Object Literal
This is the simplest and most common way to create an object.
2. Using the
ObjectConstructorYou can create an object using the
Objectconstructor.3. Using a Constructor Function
A constructor function is a reusable template for creating objects.
4. Using ES6 Classes
The
classsyntax is a more modern and readable way to define reusable object templates.5. Using
Object.createThis creates a new object with the specified prototype object.
6. Using Factory Functions
A factory function is a function that returns a new object.
Summary Table
Object.createEach method has its use case, depending on the complexity and reusability of the objects you're working with.